import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken,setToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 115000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      console.log("发送前的token:"+getToken())
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['X-Token'] = getToken()
    }
    console.log(config)
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {

    console.log("本次请求返回的结果")
    console.log(response)

    const res = response.data

    /**
     * 所有的请求的响应都要经过此处返回,因为每次请求都要带token,所以呢
     * 只要一次请求的token失效了,后端就可以通过
     */

    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 0) { //登录失败
      Message({
        message: res.msg,
        type: 'error',
        duration: 5 * 1000
      })

      // 50008:非法的token; 50012:其他客户端登录了;  50014:Token 过期了;
      //因为我的是单人应用,自己来用,不存在token中途废弃,所以这里就不去写了
      // if (res.code === 2 ||res.code===3) {//非法的token或者过期的token或者未携带令牌
      //   // to re-login
      //   MessageBox.confirm(res.msg, '提示', {
      //     confirmButtonText: '重新登陆',
      //     cancelButtonText: '取消',
      //     type: 'warning'
      //   }).then(() => {
      //     store.dispatch('user/resetToken').then(() => {
      //       location.reload()
      //     })
      //   })
      // }


      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      if(response.headers['X-Token']!==null&&response.headers['X-Token']!==undefined) {
        console.log("更新了token")
        setToken(response.headers['X-Token'])//更新token
      }
      return res
    }
  },
  error => {
    console.log('错误:' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
